package com.ruike.alisurface.utils;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import com.ruike.alisurface.MyApplication;
import com.voodoo.lib_utils.L;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;

import static android.content.Context.ACTIVITY_SERVICE;

/**
 * Author: voodoo
 * CreateDate: 2020-03-27 027 下午 03:51
 * Description:
 */
public class APPUtils {

    /**
     * 检测指定包名的APK是否在运行
     *
     * @param context     上下文
     * @param packageName 指定的包名
     * @return true：活着 false：进程遇害
     */
    @SuppressLint("NewApi")
    public static boolean isAppRunning(Context context, String packageName) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
            L.i("五点一的系统");
            // Android API > 4.4 (KITKAT)
            List<String> recentTaskList = CmdUtils.getRecentTaskList();
            if (CmdUtils.getRecentTaskList().size() > 0) {
                for (String recentTaskPackageName : recentTaskList) {
                    if (recentTaskPackageName.contains(packageName)) {
                        return true;
                    }
                }
            }
        } else {
            ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
            if (list.size() > 0) {
                for (ActivityManager.RunningTaskInfo info : list) {
                    if (info.topActivity.getPackageName().equals(packageName) || info.baseActivity.getPackageName().equals(packageName)) {
                        return true;
                    }
                }
            }
        }
        return false;

    }


    /**
     * 获取已安装应用的 uid，-1 表示未安装此应用或程序异常
     *
     * @param context     上下文
     * @param packageName 应用的包名
     * @return 指定包的uid
     */
    public static int getPackageUid(Context context, String packageName) {
        try {
            ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(packageName, 0);
            if (applicationInfo != null) {
                return applicationInfo.uid;
            }
        } catch (Exception e) {
            return -1;
        }
        return -1;
    }

    /**
     * 判断某一 uid 的程序是否有正在运行的进程，即是否存活
     *
     * @param context 上下文
     * @param uid     已安装应用的 uid
     * @return true 表示正在运行，false 表示没有运行
     */
    public static boolean isProcessRunning(Context context, int uid) {
        ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServiceInfos = am.getRunningServices(200);
        if (runningServiceInfos.size() > 0) {
            for (ActivityManager.RunningServiceInfo appProcess : runningServiceInfos) {
                if (uid == appProcess.uid) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断指定包名的安装包是否已安装
     *
     * @param context     上下文
     * @param pachageName 包名
     * @return 是否已经安装
     */
    public static boolean isAppInstalled(Context context, String pachageName) {
        PackageManager pm = context.getPackageManager();
        boolean installed = false;
        try {
            pm.getPackageInfo(pachageName, PackageManager.GET_ACTIVITIES);
            installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            installed = false;
        }
        return installed;
    }

    /**
     * 打开指定的APK
     *
     * @param context     上下文
     * @param packageName 要打开的程序的包名
     * @return 是否启动成功
     */
    public static boolean openPackage(Context context, String packageName) {
        try {
            Intent LaunchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
            LaunchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(LaunchIntent);
            return true;
        } catch (Exception e) {
            L.i(e.toString());
            return false;
        }
    }

    /**
     * 静默安装
     */
    public static boolean clientInstall(String apkPath) {
        PrintWriter PrintWriter = null;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("su");
            PrintWriter = new PrintWriter(process.getOutputStream());
            PrintWriter.println("chmod 777 " + apkPath);
            PrintWriter.println("export LD_LIBRARY_PATH=/vendor/lib:/system/lib");
            PrintWriter.println("pm install -r -d " + apkPath); // -r 保留先前应用数据 -d 允许降级安装
            PrintWriter.flush();
            PrintWriter.close();
            int value = process.waitFor();
            return value == 0;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
        return false;
    }

    /**
     * 干死某个APK
     *
     * @param context     上下文
     * @param packageName 包名
     */
    public static void stopAppByKill(Context context, String packageName) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (activityManager != null) {
            activityManager.killBackgroundProcesses(packageName);
        }
    }

    // ////////////////////////////////////////// 此处修改 //////////////////////////////////////////

    /**
     * 卸载程序
     *
     * @param packageName 程序包名
     * @return 卸载结果 是否成功
     */
    public static boolean uninstallApk(String packageName) {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("su");
            PrintWriter printWriter = new PrintWriter(process.getOutputStream());
            printWriter.println("pm uninstall " + packageName);
            printWriter.flush();
            printWriter.close();
            int value = process.waitFor();
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
    }

    /**
     * 查询指定包名安装包的路径
     *
     * @param context     上下文
     * @param pachageName 指定的包名，如果为空字符串，则获取当前apk的路径
     * @return 指定包的apk绝对路径
     */
    public static String getApkPath(Context context, String pachageName) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(pachageName.isEmpty() ? context.getPackageName() : pachageName, PackageManager.GET_META_DATA);
            ApplicationInfo applicationInfo = packageInfo.applicationInfo;
            return applicationInfo.sourceDir; // 获取当前apk包的绝对路径
        } catch (PackageManager.NameNotFoundException e) {
            return "";
        }
    }

    /**
     * 获取指定apk的版本名称
     *
     * @param context 上下文
     * @param apkPath APK的路径地址
     * @return 版本名
     */
    public static String getApkVersionName(Context context, String apkPath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo pkgInfo = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        if (pkgInfo != null) {
            return pkgInfo.versionName; // 得到版本信息
        }
        return "-1";
    }

    /**
     * 获取指定apk的版本号
     *
     * @param context 上下文
     * @param apkPath APK的路径地址
     * @return 版本号，获取不到的话返回-1
     */
    public static int getApkVersionCode(Context context, String apkPath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo pkgInfo = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        if (pkgInfo != null) {
            return pkgInfo.versionCode; // 得到版本信息
        }
        return -1;
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * 重启机器
     */
    public static void RestBoot() {
        L.i("重启机器");
        exec("reboot");

    }

    private static String exec(String command) {

        Process process = null;
        BufferedReader reader = null;
        InputStreamReader is = null;
        DataOutputStream os = null;

        try {
            process = Runtime.getRuntime().exec("su");
            is = new InputStreamReader(process.getInputStream());
            reader = new BufferedReader(is);
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(command + "\n");
            os.writeBytes("exit\n");
            os.flush();
            int read;
            char[] buffer = new char[4096];
            StringBuilder output = new StringBuilder();
            while ((read = reader.read(buffer)) > 0) {
                output.append(buffer, 0, read);
            }
            process.waitFor();
            return output.toString();
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (os != null) {
                    os.close();
                }

                if (is != null) {
                    is.close();
                }

                if (reader != null) {
                    reader.close();
                }

                if (process != null) {
                    process.destroy();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
